﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.project.service.impl;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.hh.bss.base.*;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.SystemConstant;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.config.Environment;
import com.hh.bss.project.dao.*;
import com.hh.bss.project.entity.*;
import com.hh.bss.project.service.*;
import com.hh.bss.project.vo.query.*;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.util.*;




@Service
@Transactional
public class ContractJobCvOfferServiceImpl extends BaseBusinessService<ContractJobCvOffer,java.lang.Integer>  implements ContractJobCvOfferService<ContractJobCvOffer,java.lang.Integer>{

	private ContractJobCvOfferDao contractJobCvOfferDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setContractJobCvOfferDaoImpl(ContractJobCvOfferDao dao) {
		this.contractJobCvOfferDao = dao;
	}
	private CvService cvService;
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}
	public EntityDao getEntityDao() {
		return this.contractJobCvOfferDao;
	}
	private ContractJobCvRecomService contractJobCvRecomService;
	
	@Autowired(required=true)
	private ContractJobOfferPartnerService contractJobOfferPartnerService;
	
	@Autowired(required=true)
	private ContractJobService contractJobService;
	
	public void setContractJobCvRecomServiceImpl(ContractJobCvRecomService service) {
		this.contractJobCvRecomService = service;
	}
	
	
	
	@Transactional(readOnly=true)
	public Page findPage(ContractJobCvOfferQuery query) {
		return contractJobCvOfferDao.findPage(query);
	}
	public Page findJobCvOfferPage(ContractJobCvOfferQuery query){
		return contractJobCvOfferDao.findJobCvOfferPage(query);
	}
	
	public Page findCvOfferPage(ContractJobCvOfferQuery query) {
		// TODO Auto-generated method stub
		return contractJobCvOfferDao.findCvOfferPage(query);
	}
	public void update(ContractJobCvOffer ContractJobCvOffer) throws DataAccessException{
		//更新试用期到期日(如果有实际上班日期 和 试用期时长 更新 试用期到期日)
		if(ContractJobCvOffer.getCheckinD() !=null){
			//设置试用期到期日
			Integer amount = 0;
			if(ContractJobCvOffer.getTrial() !=null){
				amount = ContractJobCvOffer.getTrial();
			}
			Date td = DateHelper.add(ContractJobCvOffer.getCheckinD(), DateHelper.MONTH, amount);
			ContractJobCvOffer.setExpiredD(DateHelper.add(td, DateHelper.DAY, -1));
		}else {
			//没有时间上班日期 ondutyDString
			if(ContractJobCvOffer.getOndutyD() !=null){
				//设置试用期到期日
				Integer amount = 0;
				if(ContractJobCvOffer.getTrial() !=null){
					amount = ContractJobCvOffer.getTrial();
					Date td = DateHelper.add(ContractJobCvOffer.getOndutyD(), DateHelper.MONTH, amount);
					ContractJobCvOffer.setExpiredD(DateHelper.add(td, DateHelper.DAY, -1));
				}
			}
		}
		contractJobCvOfferDao.update(ContractJobCvOffer);
		contractJobCvOfferDao.flush();
		
		ContractJobCvRecom contractJobCvRecom=new ContractJobCvRecom();
		contractJobCvRecom.setId(ContractJobCvOffer.getRecomId());
		//设置状态，转换
		
		if((new Integer(3)).equals(ContractJobCvOffer.getStatus())) {
			contractJobCvRecom.setProjectCvStatus(SearchProjectCv.STATUS_OFFER_NOPASS);
			contractJobCvRecom.setStatus(SearchProjectCv.STATUS_OFFER_NOPASS);
		}
		else if ((new Integer(1)).equals(ContractJobCvOffer.getStatus())&&ContractJobCvOffer.getExpiredD()!=null&&(new Date()).after(ContractJobCvOffer.getExpiredD())&&ContractJobCvOffer.getCheckinD()!=null){
			//已经上班,且保证期已过，实际上班日期已填-保证期通过
			contractJobCvRecom.setProjectCvStatus(SearchProjectCv.STATUS_OFFER_PASS);
			contractJobCvRecom.setStatus(SearchProjectCv.STATUS_OFFER_PASS);
		} else if ((new Integer(2)).equals(ContractJobCvOffer.getStatus())){
			//人选拒绝-不考虑
			contractJobCvRecom.setProjectCvStatus(SearchProjectCv.STATUS_NO);
			contractJobCvRecom.setStatus(SearchProjectCv.STATUS_NO);
		}
		else {
			contractJobCvRecom.setProjectCvStatus(SearchProjectCv.STATUS_OFFER);
			contractJobCvRecom.setStatus(SearchProjectCv.STATUS_OFFER);
		}	    
		contractJobCvRecomService.updateRecomStatus(contractJobCvRecom);
	}
	public void save(ContractJobCvOffer ContractJobCvOffer) throws DataAccessException{
		
		Object[] os={ContractJobCvOffer.getRecomId()};
		//检查是否受保护的人选
		//List l=contractJobCvOfferDao.getJdbcDao().findByQuery("select contract_job_cv_recom a,cv b,",os,new MapObjectRowMapper());
		ContractJobCvRecom 		oldContractJobCvRecom=(ContractJobCvRecom)contractJobCvRecomService.getById(ContractJobCvOffer.getRecomId());
		if (oldContractJobCvRecom!=null){
			Cv cv=cvService.getById(oldContractJobCvRecom.getCvId());
			if (cvService.isProtectCv(oldContractJobCvRecom.getCvId()))  throw new RuntimeException("人选["+cv.getCvName()+"]受到保护，无法添加Offer。"); 
		}
		
		
		//检查是否有推荐过
		
		
		List l=contractJobCvOfferDao.getHibernateTemplate().find("from ContractJobCvOffer t where t.recomId=? order by t.createDt desc ",os);
		//if(l!=null&&l.size()>0) throw new RuntimeException("人选已经添加过offer，不能重复添加");
		if(l!=null&&l.size()>0) {
			ContractJobCvOffer oldContractJobCvOffer=(ContractJobCvOffer)l.get(0);
			if (oldContractJobCvOffer.getStatus()==0){
				throw new RuntimeException("人选已经添加过offer，不能重复添加");
			}else if(oldContractJobCvOffer.getStatus()== 1){
				if(oldContractJobCvOffer.getExpiredD() != null){
					   if(oldContractJobCvOffer.getExpiredD().compareTo(new Date()) > 0){
					    	
					    	throw new RuntimeException("人选已经上班,且还在保证期内.不能新增Offer");
					    }
					      
				}
				/*
				if(oldContractJobCvOffer.getCheckinD() !=null){
					Date checkinD = oldContractJobCvOffer.getCheckinD();
				    Integer m = oldContractJobCvOffer.getTrial();
				    Integer check = checkinD.getMonth();
				    checkinD.setMonth(m+check);
				    if(checkinD.compareTo(new Date()) > 0){
				    	
				    	throw new RuntimeException("人选已经上班,且还在保证期内.不能新增Offer");
				    }
				      
				   
				}else if(oldContractJobCvOffer.getOndutyD() !=null){
					Date checkinD = oldContractJobCvOffer.getOndutyD();
				    Integer m = oldContractJobCvOffer.getTrial();
				    Integer check = checkinD.getMonth();
				    checkinD.setMonth(m+check);
				    if(checkinD.compareTo(new Date()) > 0){
				    	throw new RuntimeException("人选已经上班,且还在保证期内.不能新增Offer");
				    }
				}
				
			*/}
		}
		//设置员工的试用期到期日 (如果有时间上班日期 根据时间上班日期判断 如果没有 则根据 预估)
		if(ContractJobCvOffer.getCheckinD() !=null){
			//设置试用期到期日
			Integer amount = 0;
			if(ContractJobCvOffer.getTrial() !=null){
				amount = ContractJobCvOffer.getTrial();
			}
			Date td = DateHelper.add(ContractJobCvOffer.getCheckinD(), DateHelper.MONTH, amount);
			ContractJobCvOffer.setExpiredD(DateHelper.add(td, DateHelper.DAY, -1));
		}else {
			//没有时间上班日期 ondutyDString
			if(ContractJobCvOffer.getOndutyD() !=null){
				//设置试用期到期日
				Integer amount = 0;
				if(ContractJobCvOffer.getTrial() !=null){
					amount = ContractJobCvOffer.getTrial();
					Date td = DateHelper.add(ContractJobCvOffer.getOndutyD(), DateHelper.MONTH, amount);
					ContractJobCvOffer.setExpiredD(DateHelper.add(td, DateHelper.DAY, -1));
				}
			}
		}
		contractJobCvOfferDao.save(ContractJobCvOffer);
		contractJobCvOfferDao.flush();
		
		ContractJobCvRecom contractJobCvRecom=new ContractJobCvRecom();
		contractJobCvRecom.setId(ContractJobCvOffer.getRecomId());
		contractJobCvRecom.setProjectCvStatus(SearchProjectCv.STATUS_OFFER);
		contractJobCvRecom.setStatus(SearchProjectCv.STATUS_OFFER);
		contractJobCvRecomService.updateRecomStatus(contractJobCvRecom);
	}
	public void saveFile(MultipartHttpServletRequest multipartRequest,
			MultipartFile multipartFile, ContractJobCvOffer ContractJobCvOffer) {
		// TODO Auto-generated method stub
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");     
		  
		//把公司id也加到目录里
	       String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.JOBOFFER+"/"+dateformat.format(new Date())+"/"+"offerfile_"+ContractJobCvOffer.getId();      
	       /**得到文件保存目录的真实路径**/     
	       String fileRealPathDir = multipartRequest.getSession().getServletContext().getRealPath(fileWebPathDir);     
	       /**根据真实路径创建目录**/     
	       File fileSaveDir = new File(fileRealPathDir);     
	       if(!fileSaveDir.exists()) {    
	           fileSaveDir.mkdirs();     
	       }   
	       /**页面控件的文件流**/     
	       //MultipartFile multipartFile = multipartRequest.getFile("fileRes");      			       			      			       
	       /**上传文件名称**/     
	       String uploadFileName = multipartFile.getOriginalFilename();//    
	         
	       
	       /**获取文件的后缀**/     
	       String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);     
	       String preName = multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().indexOf("."));
	       // 文件类型   
	         
	       // 获取文件大小，以kB为单位   
	       long size = multipartFile.getSize();   
	       Double fSize =Math.round(size/1024.0*100)/100.0;   
	       String fileSize = Double.toString(fSize)+"KB";
	       if (fSize==0) fSize=new Double(1);
	       /**拼成完整的文件保存路径加文件**/     
	       
	       //重新命名
	       if(!StringHelper.isEmpty(suffix))uploadFileName=RandomStringUtil.getString(8)+"."+suffix;
	       else uploadFileName=RandomStringUtil.getString(8);
	       
	       String fileName = fileRealPathDir + File.separator   + uploadFileName;     
	       
	       File file = new File(fileName);      
	          
	       try {     
	           multipartFile.transferTo(file);  //将文件写入到指定的目录   
	       } catch (IllegalStateException e) {     
	           e.printStackTrace();     
	       } catch (IOException e) {            
	           e.printStackTrace();     
	       }    
	       //multipartFile.g
	       ContractJobCvOffer.setOfferFile(fileWebPathDir+"/"+ uploadFileName);
	}
	@Override
	public void saveToOfferRole(ContractJobCvOffer contractJobCvOffer) {
		ContractJobCvRecom jobCvRecom = (ContractJobCvRecom)contractJobCvRecomService.getById(contractJobCvOffer.getRecomId());
		if(jobCvRecom !=null){
			contractJobOfferPartnerService.addPartnerWithJob(jobCvRecom.getJobId());
			/*
			ContractJob  contractJob = (ContractJob)contractJobService.getById(jobCvRecom.getJobId());
			if(contractJob !=null){
				if(contractJob.getJobCooper() !=null) { //职位合作人
					String [] jobCooperArr = contractJob.getJobCooper().split(",");
					for(String jobCooper : jobCooperArr){
						ContractJobOfferPartner offerPartner = new ContractJobOfferPartner();
						offerPartner.setOfferId(contractJobCvOffer.getId()); //Offer Id
						offerPartner.setAccount(jobCooper);
						offerPartner.setRole(ConstantDic.JOB_PARTNER_TYPE_PC); //PC(合作顾问)
						offerPartner.setCreator(contractJobCvOffer.getCreator());
						offerPartner.setCreateDt(contractJobCvOffer.getCreateDt());
						if(!contractJobOfferPartnerService.checkSameRoleAndAccount(offerPartner)){
							contractJobOfferPartnerService.save(offerPartner);
						}
					}
				}
				
				if(contractJob.getJobAssist() != null){ //支持助理
					 //职位合作人
					String [] jobAssistArr = contractJob.getJobAssist().split(",");
					for(String jobAssist : jobAssistArr){
						ContractJobOfferPartner offerPartner = new ContractJobOfferPartner();
						offerPartner.setOfferId(contractJobCvOffer.getId()); //Offer Id
						offerPartner.setAccount(jobAssist);
						offerPartner.setRole(ConstantDic.JOB_PARTNER_TYPE_BA); //BA(支持助理)
						offerPartner.setCreator(contractJobCvOffer.getCreator());
						offerPartner.setCreateDt(contractJobCvOffer.getCreateDt());
						if(!contractJobOfferPartnerService.checkSameRoleAndAccount(offerPartner)){
							contractJobOfferPartnerService.save(offerPartner);
						}
					}
				
				}
				if(contractJob.getJobManager() !=null){
					ContractJobOfferPartner offerPartner = new ContractJobOfferPartner();
					offerPartner.setOfferId(contractJobCvOffer.getId()); //Offer Id
					offerPartner.setAccount(contractJob.getCreator());
					offerPartner.setRole(ConstantDic.JOB_PARTNER_TYPE_MC); //MC(负责人)
					offerPartner.setCreator(contractJobCvOffer.getCreator());
					offerPartner.setCreateDt(contractJobCvOffer.getCreateDt());
					if(!contractJobOfferPartnerService.checkSameRoleAndAccount(offerPartner)){
						contractJobOfferPartnerService.save(offerPartner);
					}
				}
			}
		*/}
	}
	@Override
	public List exportCvOfferList(ContractJobCvOfferQuery query) {
		// TODO Auto-generated method stub
		return contractJobCvOfferDao.exportCvOfferList(query);
	}
	@Override
	public List findJobCvOffer(ContractJobCvOfferQuery query) {
		// TODO Auto-generated method stub
		return contractJobCvOfferDao.findJobCvOffer(query);
	}
	
}
